package com.pinusmusic.web.serlvet;

import com.pinusmusic.domain.*;
import com.pinusmusic.service.MusicService;
import com.pinusmusic.service.SingerService;
import com.pinusmusic.service.impl.MusicServiceImpl;
import com.pinusmusic.service.impl.SingerServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.ObjectInputFilter;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

//HttpServletRequest request, HttpServletResponse response
@WebServlet("/music/*")
public class MusicServlet extends BaseServlet {
    private MusicService musicService = new MusicServiceImpl();
    private SingerService singerService = new SingerServiceImpl();

    public void findMusicsByMid(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        Integer mid = Integer.valueOf(request.getParameter("mid")) ;
        Music musicByMid = musicService.findMusicByMid(mid);
        musicByMid.setMusicpath( URLDecoder.decode(musicByMid.getMusicpath(),"utf-8"));
        writeValue(response,musicByMid);
    }
    public void getInput(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        String name = (String) request.getSession().getAttribute("name");
        writeValue(response,name);
    }
    //获取不在歌单中的歌曲
    public void findMusicByPage(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
        String curStr = request.getParameter("currentPage");
        String mlid = request.getParameter("mlid");
        if (curStr==null || curStr.equals("") || curStr.equals("0")) curStr="1";
        int currentPage = Integer.parseInt(curStr);
        //设置每次查询条数
        int rows = 3;
        PageBean<Music> pageBean = musicService.findMusicByPage(currentPage, rows,Integer.parseInt(mlid));
        int totalCount = musicService.getTotalCount(Integer.parseInt(mlid));
        pageBean.setTotalCount(totalCount);
        int totalPage = totalCount%rows==0?(totalCount/rows):(totalCount/rows)+1;
        pageBean.setTotalPage(totalPage);
        Map<Integer,List<String>> map=new HashMap<>();
        int i=0;
        for (Music m:pageBean.getList()) {
            Singer singerBySid = singerService.findSingerBySid(m.getSid());
            List<String> list = new ArrayList<>();
            list.add(m.getMusicname());
            list.add(singerBySid.getSingername());
            map.put(i,list);
            i++;
        }
        pageBean.setMap(map);
        writeValue(response,pageBean);
    }
    //获取歌单中的歌曲
    public void findMusicInListByPage(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
        String curStr = request.getParameter("currentPage");
        String mlid = request.getParameter("mlid");
        if (curStr==null || curStr.equals("") || curStr.equals("0")) curStr="1";
        int currentPage = Integer.parseInt(curStr);
        //设置每次查询条数
        int rows = 8;
        //
        PageBean<Music> pageBean = musicService.findMusicInListByPage(currentPage, rows,Integer.parseInt(mlid));
        //
        int totalCount = musicService.getCount(Integer.parseInt(mlid));
        pageBean.setTotalCount(totalCount);
        int totalPage = totalCount%rows==0?(totalCount/rows):(totalCount/rows)+1;
        pageBean.setTotalPage(totalPage);
        Map<Integer,List<String>> map=new HashMap<>();
        int i=0;
        for (Music m:pageBean.getList()) {
            Singer singerBySid = singerService.findSingerBySid(m.getSid());
            List<String> list = new ArrayList<>();
            list.add(m.getMusicname());
            list.add(singerBySid.getSingername());
            map.put(i,list);
            i++;
        }
        pageBean.setMap(map);
        System.out.println(pageBean);
        writeValue(response,pageBean);
    }

    public void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        ResultInfo info=musicService.musicDelete(req, resp);
        this.writeValue(resp,info);
        System.out.println("音乐删除状态"+info.isFlag());
    }

    public void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        ResultInfo info=musicService.musicUpdate(req, resp);
        Singer singer = (Singer) req.getSession().getAttribute("singer");
        if (info.isFlag()){
            resp.sendRedirect(req.getContextPath()+"/adminHtml/music_list.html?sid="+singer.getSid());
        }
    }
    public void upload(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        ResultInfo info=musicService.musicUpload(req, resp);
        Singer singer = (Singer) req.getSession().getAttribute("singer");
        if (info.isFlag()){
            resp.sendRedirect(req.getContextPath()+"/adminHtml/music_list.html?sid="+singer.getSid());
        }
    }
    //获取要修改的歌曲
    public void getOne(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String mid = req.getParameter("mid");
        Music music = musicService.findMusicByMid(Integer.parseInt(mid));
        req.getSession().setAttribute("music",music);
        writeValue(resp,music);
    }
    /**
     * 歌曲的模糊查询
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void findMusicsByName(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
        //获取到用户输入的内容
        String name = URLDecoder.decode(request.getParameter("name"),"utf-8");
        //将输入的内容保存
        request.getSession().setAttribute("name",name);
        //获取前端得到的当前页面
        String curStr = request.getParameter("currentPage");
        System.out.println("findMusicsByName获取的name："+name);
        //一开始就为第一页
        if (curStr==null || curStr.equals("") || curStr.equals("0")) curStr="1";
        int currentPage = Integer.parseInt(curStr);
        //设置每次查询五条;
        int rows = 5;
        PageBean<Music> pageBean = musicService.findMusicsByName(currentPage, rows, name);
        System.out.println("findMusicsByName的结果:"+pageBean);
        writeValue(response,pageBean);
    }
    //根据歌词模糊查询歌曲
    public void findMusicsByLyrics(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取到用户输入的内容
        String name = URLDecoder.decode(req.getParameter("name"),"utf-8");
        //将输入的内容保存
        req.getSession().setAttribute("name",name);
        //获取前端得到的当前页面
        String curStr = req.getParameter("currentPage");
        System.out.println("findMusicsByLyrics获取的name："+name);
        //一开始就为第一页
        if (curStr==null || curStr.equals("") || curStr.equals("0")) curStr="1";
        int currentPage = Integer.parseInt(curStr);
        //设置每次查询五条;
        int rows = 5;
        PageBean<Music> pageBean = musicService.findMusicsByLyrics(currentPage, rows, name);
        List<Music> list = pageBean.getList();
        if (list!=null){
            for (int i = 0; i < list.size(); i++) {
                Music music = list.get(i);
                Singer singer = singerService.findSingerBySid(music.getSid());
                music.setSinger(singer);
            }
        }
        System.out.println("findMusicsByLyrics的结果："+pageBean);
        writeValue(resp,pageBean);
    }
    //根据分类查询歌曲
    public void findMusicsBySort(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取语种
        String languageid = req.getParameter("languageid");
        if (languageid==null || languageid.equals("")) languageid="0";
        //获取风格
        String styleid = req.getParameter("styleid");
        if (styleid==null || styleid.equals("")) styleid="0";
        //获取前端得到的当前页面
        String curStr = req.getParameter("currentPage");
        //一开始就为第一页
        if (curStr==null || curStr.equals("") || curStr.equals("0")) curStr="1";
        int currentPage = Integer.parseInt(curStr);
        System.out.println("语种："+languageid+",风格："+styleid+",当前页："+curStr);
        //设置每次查询五条;
        int rows = 5;
        PageBean<Music> pageBean = musicService.findMusicsBySort(currentPage, rows, Integer.parseInt(languageid),Integer.parseInt(styleid));
        List<Music> list = pageBean.getList();
        if (list!=null){
            for (int i = 0; i < list.size(); i++) {
                Music music = list.get(i);
                Singer singer = singerService.findSingerBySid(music.getSid());
                music.setSinger(singer);
            }
        }
        System.out.println("findMusicsBySort的结果："+pageBean);
        writeValue(resp,pageBean);
    }
    public void MusicPre(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Music> musiclist =(List<Music>) req.getSession().getAttribute("musiclist");
        Music nowmusic =(Music) req.getSession().getAttribute("nowmusic");
        int i = musiclist.indexOf(nowmusic);
        if(i==0){
            i=musiclist.size()-1;
        }else {
            i--;
        }
        nowmusic=musiclist.get(i);
        req.getSession().setAttribute("nowmusic",nowmusic);
        writeValue(resp,nowmusic);
    }
    public void MusicNext(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Music> musiclist =(List<Music>) req.getSession().getAttribute("musiclist");
        Music nowmusic =(Music) req.getSession().getAttribute("nowmusic");
        int i = musiclist.indexOf(nowmusic);
        if(i==musiclist.size()-1){
            i=0;
        }else {
            i++;
        }
        nowmusic=musiclist.get(i);
        req.getSession().setAttribute("nowmusic",nowmusic);
        System.out.println(nowmusic);
        writeValue(resp,nowmusic);
    }
    public void addMusic(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Music> musiclist = (List<Music>) req.getSession().getAttribute("musiclist");
        Integer mid =Integer.parseInt(req.getParameter("mid")) ;
        Music musicByMid = musicService.findMusicByMid(mid);
        System.out.println("musicById"+musicByMid);
        boolean flag=false;
        if (musiclist!=null){
            for (int i = 0; i < musiclist.size(); i++) {
                if (musiclist.get(i).getMid().equals(musicByMid.getMid())){
                    flag=true;
                    break;
                }
            }
            if (!flag){
                musiclist.add(musicByMid);
            }}
        else {
            musiclist.add(musicByMid);
        }
        System.out.println(musiclist);
        req.getSession().setAttribute("musiclist",musiclist);
        req.getSession().setAttribute("nowmusic",musicByMid);
        writeValue(resp,musicByMid);
    }
    public void setsession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object musiclist = req.getSession().getAttribute("musiclist");
        if (musiclist==null){
            musiclist = new ArrayList<Music>();
            req.getSession().setAttribute("musiclist",musiclist);
        }
    }
    public void showMusicList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Music> musiclist = (List<Music>) req.getSession().getAttribute("musiclist");
        Music nowmusic = (Music) req.getSession().getAttribute("nowmusic");
        List<Object>list=new ArrayList<>();
        list.add(nowmusic);
        list.add(musiclist);
        writeValue(resp,list);
    }
    public void findMusicByMid(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        MusicInfo musicInfo = new MusicInfo();
        Integer mid = Integer.parseInt(request.getParameter("mid")) ;
        Music musicByMid = musicService.findMusicByMid(mid);
        musicInfo.setMusic(musicByMid);
        Singer singerByMid = musicService.findSingerByMid(musicByMid.getSid());
        musicInfo.setSinger(singerByMid);
        MusicStyle ms = musicService.findMusicStyle(musicByMid.getMusicstyleid());
        musicInfo.setMusicstyle(ms.getMusicstylename());
        MusicLanguage ml = musicService.findMusicLang(musicByMid.getMusiclanguageid());
        musicInfo.setMusiclanguage(ml.getMusiclanguagename());
        musicByMid.setMusicpath( URLDecoder.decode(musicByMid.getMusicpath(),"utf-8"));
        writeValue(response,musicInfo);
    }
    public void findCommentsByMid(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        MusicInfo musicInfo = new MusicInfo();
        Integer mid = Integer.parseInt(req.getParameter("mid")) ;
        Music musicByMid = musicService.findMusicByMid(mid);
        musicInfo.setMusic(musicByMid);
        Singer singerByMid = musicService.findSingerByMid(musicByMid.getSid());
        musicInfo.setSinger(singerByMid);
        MusicStyle ms = musicService.findMusicStyle(musicByMid.getMusicstyleid());
        musicInfo.setMusicstyle(ms.getMusicstylename());
        MusicLanguage ml = musicService.findMusicLang(musicByMid.getMusiclanguageid());
        musicInfo.setMusiclanguage(ml.getMusiclanguagename());
        musicByMid.setMusicpath( URLDecoder.decode(musicByMid.getMusicpath(),"utf-8"));
        List<CommentInf> list = new ArrayList<>();
        List<Comment> comments = musicService.findCommentsByMid(mid);
        for (Comment c:comments) {
            CommentInf commentInf = new CommentInf();
            User user = musicService.findUserByUid(c.getUid());
            int commentCounts = musicService.findCommentsCounts(mid);
            commentInf.setComment(c);
            commentInf.setUser(user);
            commentInf.setCounts(commentCounts);
            commentInf.setMusicInfo(musicInfo);
            list.add(commentInf);
        }
//        for (int i = 0; i < list.size(); i++) {
//            CommentInf commentInf1 = list.get(i);
//            System.out.println("评论"+(i+1)+commentInf1.getComment());
//        }
        writeValue(resp,list);
    }
    public void addComment(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<User> list = (List<User>) req.getSession().getAttribute("user");
        User user = list.get(0);
        Comment comment = new Comment();
        if (user.getUid()!=null){
            Integer mid = Integer.parseInt(req.getParameter("mid"));
            System.out.println("mid:"+mid);
            comment.setMid(mid);
            String content = req.getParameter("content");
            System.out.println("content:"+content);
            comment.setCommenttext(content);
            comment.setUid(user.getUid());
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            comment.setData(sdf.format(date));
            musicService.addComment(comment);
        }
        writeValue(resp,comment);
    }
    public void rankByComments(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<MusicRank> mrList = new ArrayList<>();
        List<Music> list = musicService.findAllMusic();
        for (Music m : list) {
            MusicRank mr = new MusicRank();
            int counts = musicService.findCommentsCounts(m.getMid());
            Singer singer = musicService.findSingerBySid(m.getSid());
            mr.setSinger(singer);
            mr.setMusic(m);
            mr.setCommentsCount(counts);
            mrList.add(mr);
        }
        Comparator<MusicRank> byCounts = new Comparator<MusicRank>(){
            @Override
            public int compare(MusicRank o1, MusicRank o2) {
                return o2.getCommentsCount()-o1.getCommentsCount();
            }
        };
        Collections.sort(mrList,byCounts);
        writeValue(resp,mrList);
    }
    public void rankByFavor(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<FavorRank> mrList = new ArrayList<>();
        List<Music> list = musicService.findAllMusic();
        for (Music m : list) {
            FavorRank fr = new FavorRank();
            int counts = musicService.findFavorsCounts(m.getMid());
            Singer singer = musicService.findSingerBySid(m.getSid());
            fr.setSinger(singer);
            fr.setMusic(m);
            fr.setFavorCount(counts);
            mrList.add(fr);
        }
        Comparator<FavorRank> byCounts = new Comparator<FavorRank>(){
            @Override
            public int compare(FavorRank o1, FavorRank o2) {
                return o2.getFavorCount()-o1.getFavorCount();
            }
        };
        Collections.sort(mrList,byCounts);
        writeValue(resp,mrList);
    }
    public void changelist(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer mlid = Integer.valueOf(req.getParameter("mlid"));
        List<Music> musiclist=musicService.findMusicByMlid(mlid);
        req.getSession().setAttribute("musiclist",musiclist);
        req.getSession().setAttribute("nowmusic",musiclist.get(0));
        writeValue(resp,musiclist.get(0));
    }

}
